package com.example.saiaadmin.service.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.saiaadmin.entry.EbSystemUser;
import com.example.saiaadmin.mapper.EbSystemUserMapper;
import com.example.saiaadmin.po.CusterUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 实现security的UserDetailsService
 * springsecurity配置文件中的hasRole("")不能以ROLE开头，比如ROLE_USER就是错的，springsecurity会默认加上，但数据库的权限字段必须是ROLE_开头，否则读取不到
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private EbSystemUserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(null == username){
            throw new UsernameNotFoundException(username);
        }
        LambdaQueryWrapper<EbSystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EbSystemUser::getUsername,username);
        EbSystemUser  ebuser = userMapper.selectOne(queryWrapper);
        if(null == ebuser){
            throw new UsernameNotFoundException(username);
        }
        return new CusterUserDetails(ebuser);
    }
}
